// pages/business/index/index.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var sceneres = {}
var app = getApp()
var winScale = 750 / app.data.deviceInfo.windowWidth
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cert_flag: true,
    img_loading: false,
    cert_bg_path: 'https://img-oss.shihanbainian.com/upload_dev/images/0/2/8/0283f6d7da9ab9045737462265b06e6f.jpg'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();
    app.wechatSwitch().then(function(wechat_switch) { //是否打开微信授权开关
      app.commonLogin(sceneres, wechat_switch)
    })
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        promotefresh: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.agentHome();
  },

  /**
   * 页面事件
   */
  agentHome: function() {
    var that = this
    shihan.sendRequest(config.agent_home, 'POST', {})
      .then(function(response) {
        if (response.data.code == 0) {
          if (response.data.data.sh_brands.length >= 6) {
            response.data.data.sh_brands = response.data.data.sh_brands.slice(0,5);
            response.data.data.sh_brands = response.data.data.sh_brands.concat({
              sh_id: '',
              sh_logo: "https://img-oss.shihanbainian.com/upload_dev/images/8/3/5/835d5d3d9be5d0f4a8155ed324509cfa.png",
              sh_name: "查看更多",
              sh_status: 1,
              sh_url: "",
            })
          }
          that.setData({
            agent_home: response.data.data
          })
          if (!response.data.data.sh_nick_name) { //判断是否清除token
            wx.setStorageSync('token', '');
          }
          config.nickName = response.data.data.sh_nick_name;
          if (response.data.data.sh_auth_arr) {
            const downloadmask1 = wx.downloadFile({
              url: response.data.data.sh_auth_arr.sh_image,
              success: function(res) {
                that.setData({
                  cardbgPath: res.tempFilePath
                })
                const downloadmask2 = wx.downloadFile({
                  url: response.data.data.sh_auth_arr.sh_headimgurl,
                  success: function(res) {
                    that.setData({
                      userimgPath: res.tempFilePath
                    })
                    if (that.data.img_loading) {
                      that.drawCanvas(that);
                    }
                  }
                })
              }
            })
          }
          wx.setStorage({ //代理商资料存到storage，查看资料用
            key: 'mineagentinfo',
            data: {
              sh_name: response.data.data.sh_real_name,
              sh_mobile: response.data.data.sh_mobile,
              sh_id_card: response.data.data.sh_id_card,
              sh_address: response.data.data.sh_address,
              sh_agent_start_at: response.data.data.sh_agent_time
            }
          })
          wx.stopPullDownRefresh()
        }
      }, function(error) {
        console.log(error);
      });
  },
  isLogin: function() {
    var token = wx.getStorageSync('token');
    if (!token) {
      app.commonNoLogin()
    }
  },
  becomeAgent: function(e) {
    var token = wx.getStorageSync('token'),
      url = encodeURIComponent(this.data.agent_home.sh_agent_apply_url),
      is_agent = this.data.agent_home.sh_is_agent, //是否是代理商
      apply_wide = this.data.agent_home.sh_apply_wide; // 代理商申请状态 //0可申请 1审核中 2审核通过 3审核拒绝,
    if (token) {
      if (is_agent == 1) { //查看资料
        wx.navigateTo({
          url: '/pages/business/myagentinfo/myagentinfo?index=1',
        })
      } else if (is_agent == 0) { //不是代理商，跳转填写资料页面
        if (apply_wide == 0 || apply_wide == 3) {
          wx.navigateTo({
            url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + url + '&name=填写申请资料'
          })
        } else if (apply_wide == 1) {
          shihan.showToast.call(this, '申请已提交，资料正在审核中');
        }
      }
    } else {
      app.commonNoLogin()
    }
  },
  openAlliance: function() {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(this.data.agent_home.sh_explain_url) + '&name=联盟说明'
    })
  },
  userShare: function() {
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 0) {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  agentBrand: function(e) {
    var status = e.currentTarget.dataset.status,
      name = e.currentTarget.dataset.name,
      url = e.currentTarget.dataset.url;
    if (e.currentTarget.dataset.id) {
      if (status == 1) { //查看品牌介绍，可以代理
        wx.navigateTo({
          url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(url) + '&name=' + name
        })
      } else if (status == 2) { //暂不能代理
        shihan.showToast.call(this, '该品牌即将入驻，敬请期待');
      }
    } else {//查看更多代理品牌
      wx.navigateTo({
        url: '/pages/business/myagent/myagent?index=3',
      })
    }
  },
  myAgent: function() { //我的代理商
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/myagent/myagent?index=1',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  agentApply: function() { //代理商申请
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/agentapply/agentapply?index=1',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  shiftReview: function() { //转移审核
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/agentapply/agentapply?index=2',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  wantStock: function() { //我要进货
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/myorder/myorder?index=1',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  myStock: function() { //我的进货单
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/myorder/myorder?index=0',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  agentTrade: function() { //代理商进货单
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/agenttrade/agenttrade',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  storyCircle: function () { //素材库
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/storycircle/storycircle',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  sellTotal: function () { //进销统计
    var token = wx.getStorageSync('token');
    if (token) {//进销统计和添加物流公用一个页面
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/addlogistic/addlogistic?index=3',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  manageMent: function () { //返货管理
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/management/management',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  goodsTracke: function() { //产品追踪（和扫码收货，发货用同一个页面）
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/sweepcode/sweepcode?index=3',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  applyShift: function() { //申请转移
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        wx.navigateTo({
          url: '/pages/business/sweepcode/sweepcode?index=4',
        })
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  lookConcat: function() { //联系客服
    wx.navigateTo({
      url: '/pages/business/myagentinfo/myagentinfo?index=3',
    })
  },
  lookCert: function() {
    var token = wx.getStorageSync('token');
    if (token) {
      if (this.data.agent_home.sh_is_agent == 1) {
        if (this.data.agent_home.sh_auth_arr.sh_is_show == 1) {
          wx.showLoading()
          if (this.data.userimgPath) {
            this.setData({
              cert_flag: false
            })
            this.drawCanvas(this);
          } else {
            this.setData({
              img_loading: true
            })
          }
        } else {
          shihan.showToast.call(this, this.data.agent_home.sh_auth_arr.sh_hint_text);
        }
      } else {
        shihan.showToast.call(this, '请先加入微商联盟哦');
      }
    } else {
      app.commonNoLogin()
    }
  },
  certClose: function() {
    this.setData({
      cert_flag: true,
      img_loading: false
    })
  },
  drawCanvas: function(that) {
    var auth_arr = that.data.agent_home.sh_auth_arr;
    var context = wx.createCanvasContext('myCanvas');

    context.clearRect(0, 0, 600 / winScale, 900 / winScale);
    context.drawImage(that.data.cardbgPath, 0, 0, 600 / winScale, 900 / winScale);
    context.save();

    context.setFontSize(20 / winScale);
    context.setFillStyle('#863938');
    context.fillText('兹授权:', 76 / winScale, 322 / winScale);
    context.setFontSize(26 / winScale);
    context.fillText(auth_arr.sh_name, 170 / winScale, 322 / winScale);
    var width = context.measureText(auth_arr.sh_name).width;


    line(145 / winScale, (145 / winScale) + width + 25, 328 / winScale)



    var word_arr = auth_arr.sh_text.split('"' + auth_arr.sh_bold_text + '"');
    var bold_text = new String('"' + auth_arr.sh_bold_text + '"');
    var normal_text = new String(word_arr[1]);

    var bold_text_a = calc(bold_text, 0, 7);
    var bold_text_b = calc(bold_text, 7, 'big');

    var normal_text_a = calc(normal_text, 0, 20);
    var normal_text_b = calc(normal_text, 20, 'big');

    context.setFontSize(20 / winScale);
    context.fillText(word_arr[0], 76 / winScale, 360 / winScale);
    var width1 = context.measureText(word_arr[0]).width;


    context.setFontSize(24 / winScale);
    context.fillText(bold_text_a, (76 / winScale) + width1, 360 / winScale);
    context.fillText(bold_text_b, 76 / winScale, (360 / winScale) + 20);


    context.setFontSize(20 / winScale);
    var width2 = context.measureText(bold_text_b).width + 5;
    context.fillText(normal_text_a, (76 / winScale) + width2, (360 / winScale) + 20);
    context.fillText(normal_text_b, 76 / winScale, (360 / winScale) + 40);



    context.fillText('授权姓名：', 76 / winScale, 517 / winScale);
    context.fillText(auth_arr.sh_name, 200 / winScale, 517 / winScale);
    line(180 / winScale, (180 / winScale) + width + 20, 522 / winScale)

    var date_word_height = 602 / winScale,
      date_line_height = 607 / winScale;
    if (auth_arr.sh_wechat) {
      context.fillText('授权微信：', 76 / winScale, 560 / winScale);
      context.fillText(auth_arr.sh_wechat, 200 / winScale, 560 / winScale);
      var width3 = context.measureText(auth_arr.sh_wechat).width;
      line(180 / winScale, (180 / winScale) + width3 + 20, 565 / winScale);
    } else {
      date_word_height = 560 / winScale, date_line_height = 565 / winScale;
    }

    context.fillText('授权日期：', 76 / winScale, date_word_height);
    context.fillText(auth_arr.sh_auth_time, 200 / winScale, date_word_height);
    var width4 = context.measureText(auth_arr.sh_auth_time).width;
    line(180 / winScale, (180 / winScale) + width4 + 20, date_line_height)

    context.drawImage(that.data.userimgPath, 420 / winScale, 500 / winScale, 110 / winScale, 110 / winScale);



    function calc(a, b, c) {
      var item = a.split("");
      if (c == 'big') {
        c = item.length;
      }
      return item.slice(b, c).join().replace(/\,/g, '');
    }

    function line(a, b, c) {
      context.setStrokeStyle('#863938');
      context.beginPath();
      context.moveTo(a, c);
      context.lineTo(b, c);
      context.closePath();
      context.stroke();
    }

    context.restore();
    wx.hideLoading()
    context.draw();
  },
  saveImg: function() {
    var that = this
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        shihan.saveImage(res.tempFilePath); //保存图片
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.agentHome();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this
    var customerId = wx.getStorageSync('customerId');
    return {
      title: '邀请您加入世瀚百年微商联盟',
      path: '/pages/business/agentshare/agentshare?id=' + customerId,
      imageUrl: 'https://img-oss.shihanbainian.com/upload_dev/images/1/0/6/10649d54c5602973d0af562c7157d98c.jpg',
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})